package org.mozhu.rpc.transport.netty.channel;

import com.google.common.collect.Lists;
import org.mozhu.rpc.transport.UnresolvedAddress;
import org.mozhu.rpc.transport.channel.JChannel;
import org.mozhu.rpc.transport.channel.JChannelGroup;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class NettyChannelGroup implements JChannelGroup {

    private final UnresolvedAddress address;

    private final CopyOnWriteArrayList<NettyChannel> channels = new CopyOnWriteArrayList<>();

    private volatile boolean connecting = false;

    private volatile int capacity = Integer.MAX_VALUE;

    public NettyChannelGroup(UnresolvedAddress address) {
        this.address = address;
    }

    @Override
    public UnresolvedAddress remoteAddress() {
        return address;
    }

    @Override
    public JChannel next() {
        return null;
    }

    @Override
    public List<? extends JChannel> channels() {
        return Lists.newArrayList(channels);
    }

    @Override
    public boolean isEmpty() {
        return channels.isEmpty();
    }

    @Override
    public boolean add(JChannel channel) {
        return channel instanceof NettyChannel && channels.add((NettyChannel) channel);
    }

    @Override
    public boolean remove(JChannel channel) {
        return channel instanceof NettyChannel && channels.remove(channel);
    }

    @Override
    public int size() {
        return channels.size();
    }

    @Override
    public void setCapacity(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public int getCapacity() {
        return capacity;
    }

    @Override
    public boolean isConnecting() {
        return connecting;
    }

    @Override
    public void setConnecting(boolean connecting) {
        this.connecting = connecting;
    }

    @Override
    public boolean isAvailable() {
        return !channels.isEmpty();
    }

}
